// people/pages/calendar1/calendar1.js
// Page({  
//   data: {  
//     currentYear: new Date().getFullYear(),  
//     currentMonth: new Date().getMonth(),  
//     days: [], // This will be populated with the days of the current month  
//     punchCardData: {} // This will store the punch card data by date  
//   },  
  
//   onLoad: function () {  
//     this.generateDays();  
//   },  
  
//   generateDays: function () {  
//     const { currentYear, currentMonth } = this.data;  
//     const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();  
//     const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();  
  
//     let days = [];  
//     for (let i = 0; i < firstDayOfMonth; i++) {  
//       days.push({ day: '', date: '', punched: false }); // Empty days before the start of the month  
//     }  
  
//     for (let day = 1; day <= daysInMonth; day++) {  
//       days.push({  
//         day: day,  
//         date: `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`,  
//         punched: this.data.punchCardData[day] ? true : false  
//       });  
//     }  
  
//     this.setData({ days: days });  
//   },  
  
//   prevMonth: function () {  
//     const { currentYear, currentMonth } = this.data;  
//     let newMonth = currentMonth - 1;  
//     if (newMonth < 0) {  
//       newMonth = 11;  
//       this.setData({ currentYear: currentYear - 1 });  
//     }  
//     this.setData({ currentMonth: newMonth, days: [] }, () => {  
//       this.generateDays();  
//     });  
//   },  
  
//   nextMonth: function () {  
//     const { currentYear, currentMonth } = this.data;  
//     let newMonth = currentMonth + 1;  
//     if (newMonth > 11) {  
//       newMonth = 0;  
//       this.setData({ currentYear: currentYear + 1 });  
//     }  
//     this.setData({ currentMonth: newMonth, days: [] }, () => {  
//       this.generateDays();  
//     });  
//   },  
  
//   punchCard: function (e) {  
//     const date = e.currentTarget.dataset.date;  
//     const punchCardData = this.data.punchCardData;  
//     punchCardData[date] = true; // Mark as punched  
//     this.setData({ punchCardData: punchCardData }, () => {  
//       // Optionally, save the punch card data to local storage or a server  
//       wx.setStorageSync('punchCardData', punchCardData);  
//       // Regenerate days to update the punch status display  
//       this.generateDays();  
//     });  
//   }  
// });
// Page({  
//   data: {  
//     currentYear: new Date().getFullYear(),  
//     currentMonth: new Date().getMonth(),  
//     days: [], // This will be populated with the days of the current month  
//     today: new Date().getDate(), // Store today's date for easy access  
//     punchCardData: {}, // This will store the punch card data by date  
  
//   },  
  
//   onLoad: function () {  
//     this.generateDays();  
//     this.highlightToday(); // Call a function to highlight today's date  
//   },  
  
//   generateDays: function () {  
//     const { currentYear, currentMonth } = this.data;  
//     const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();  
//     const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();  
  
//     let days = [];  
//     for (let i = 0; i < firstDayOfMonth; i++) {  
//       days.push({ day: '', date: '', punched: false, isToday: false }); // Empty days before the start of the month  
//     }  
  
//     for (let day = 1; day <= daysInMonth; day++) {  
//       const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;  
//       days.push({  
//         day: day,  
//         date: dateStr,  
//         punched: this.data.punchCardData[dateStr] ? true : false,  
//         isToday: day === this.data.today // Check if this is today's date  
//       });  
//     }  
  
//     this.setData({ days: days });  
//   },  
  
//   highlightToday: function () {  
//     // This function is called to update the UI after setting the days data  
//     // In this case, it's redundant because we already set isToday in generateDays,  
//     // but it could be useful if you want to apply additional styles or logic later  
//   },  
  
//   prevMonth: function () {  
//     // ... (same as before)  
//     this.setData({ currentMonth: newMonth, days: [] }, () => {  
//       this.generateDays();  
//     });  
//   },  
  
//   nextMonth: function () {  
//     // ... (same as before)  
//     this.setData({ currentMonth: newMonth, days: [] }, () => {  
//       this.generateDays();  
//     });  
//   },  
  
//   punchCard: function (e) {  
//     const date = e.currentTarget.dataset.date;  
//     const punchCardData = { ...this.data.punchCardData }; // Create a copy to avoid mutation  
//     punchCardData[date] = true; // Mark as punched  
//     this.setData({ punchCardData: punchCardData }, () => {  
//       // Optionally, save the punch card data to local storage or a server  
//       wx.setStorageSync('punchCardData', punchCardData);  
//       // Regenerate days to update the punch status display (not strictly necessary if only updating today)  
//       // But we'll do it here for consistency with your original code  
//       this.generateDays();  
//     });  
//   }  

// });
Page({    
  data: {    
    currentYear: new Date().getFullYear(),    
    currentMonth: new Date().getMonth(),    
    days: [], // This will be populated with the days of the current month    
    today: new Date().getDate(), // Store today's date for easy access    
    punchCardData: {}, // This will store the punch card data by date    
    consecutivePunchDays: 0, // Continuous punch days  
    totalPunchDays: 0, // Total punch days  
  },    
    
  onLoad: function () {    
    this.generateDays();    
  },    
    
  generateDays: function () {    
    const { currentYear, currentMonth, today, punchCardData } = this.data;    
    const firstDayOfMonth = new Date(currentYear, currentMonth, 1).getDay();    
    const daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();    
    let consecutiveDays = 0;  
  
    let days = [];    
    for (let i = 0; i < firstDayOfMonth; i++) {    
      days.push({ day: '', date: '', punched: false, isToday: false, canPunch: false }); // Empty days before the start of the month    
    }    
    
    for (let day = 1; day <= daysInMonth; day++) {    
      const dateStr = `${currentYear}-${String(currentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;    
      const isTodayOrBefore = day <= today;  
      const isPunched = punchCardData[dateStr] ? true : false;  
      const canPunch = isTodayOrBefore && !isPunched ? true : false;  
  
      if (isPunched && consecutiveDays < (day - 1)) {  
        consecutiveDays = day - 1; // Update consecutive days only if a punch is found in a sequence  
      } else if (isPunched) {  
        consecutiveDays++;  
      } else {  
        consecutiveDays = 0; // Reset consecutive days if no punch is found  
      }  
  
      days.push({    
        day: day,    
        date: dateStr,    
        punched: isPunched,    
        isToday: day === today,    
        canPunch: canPunch  
      });    
    }  
  
    // Calculate total punch days  
    const totalPunchDays = Object.keys(this.data.punchCardData).length;  
  
    this.setData({   
      days: days,   
      //consecutivePunchDays: consecutiveDays > 0 ? consecutiveDays : 0, // Set to the last consecutive days found  
      totalPunchDays: totalPunchDays   
    });    
  },    
    
  prevMonth: function () {    
    const newMonth = (this.data.currentMonth - 1 + 12) % 12; // Handle wrap-around for January  
    this.setData({ currentMonth: newMonth, days: [] }, () => {    
      this.generateDays();    
    });    
  },    
    
  nextMonth: function () {    
    const newMonth = (this.data.currentMonth + 1) % 12; // Handle wrap-around for December  
    this.setData({ currentMonth: newMonth, days: [] }, () => {    
      this.generateDays();    
    });    
  },    
    
  //punchCard: function (e) {    
  //   const date = e.currentTarget.dataset.date;    
  //   const { punchCardData, consecutivePunchDays, totalPunchDays } = this.data;  
  //   const isToday = new Date().toISOString().split('T')[0] === date.split('-')[0] + '-' + date.split('-')[1] + '-' + date.split('-')[2];  
  
  //   if (!isToday) {  
  //     wx.showToast({  
  //       title: '不能打卡，请选择今天或之前的日期',  
  //       icon: 'none'  
  //     });  
  //     return;  
  //   }  
  
  //   if (!punchCardData[date]) {  
  //     const newPunchCardData = { ...punchCardData };  
  //     newPunchCardData[date] = true;  
  
  //     this.setData({   
  //       punchCardData: newPunchCardData,   
  //       days: this.data.days.map(day => ({ ...day, punched: day.date === date }))   
  //     }, () => {  
  //       wx.setStorageSync('punchCardData', newPunchCardData);  
  //       wx.showToast({  
  //         title: '打卡成功',  
  //         icon: 'success'  
  //       });  
  
  //       // Regenerate days to reflect the punch status in the UI  
  //       this.generateDays();  
  //     });  
  //   } else {  
  //     wx.showToast({  
  //       title: '今日已打卡',  
  //       icon: 'none'  
  //     });  
  //   }  
  // }    
  // punchCard: function (e) {  
  //   const date = e.currentTarget.dataset.date;  
  //   const { punchCardData } = this.data;  
  
  //   if (!new Date(date).toDateString() === new Date().toDateString()) {  
  //     wx.showToast({  
  //       title: '不能打卡，请选择今天或之前的日期',  
  //       icon: 'none'  
  //     });  
  //     return;  
  //   }  
  
  //   let newPunchCardData = { ...punchCardData };  
  //   let isPunched = newPunchCardData[date] ? true : false;  
  
  //   if (!isPunched) {  
  //     newPunchCardData[date] = true;  
  
  //     // 更新连续打卡天数  
  //     let consecutiveDays = 0;  
  //     const dates = Object.keys(newPunchCardData).sort();  
  //     for (let i = dates.length - 1; i >= 0; i--) {  
  //       if (new Date(dates[i]) >= new Date(dates[dates.length - 1]) - (dates.length - i) * 24 * 60 * 60 * 1000) {  
  //         consecutiveDays++;  
  //       } else {  
  //         break;  
  //       }  
  //     }  
  
  //     this.setData({  
  //       punchCardData: newPunchCardData,  
  //       days: this.data.days.map(day => ({ ...day, punched: day.date === date })),  
  //       consecutivePunchDays: consecutiveDays, // 更新连续打卡天数  
  //       totalPunchDays: Object.keys(newPunchCardData).length // 更新总打卡天数（虽然这里可能已经是正确的了，但为了确保一致性还是更新一下）  
  //     }, () => {  
  //       wx.setStorageSync('punchCardData', newPunchCardData);  
  //       wx.showToast({  
  //         title: '打卡成功',  
  //         icon: 'success'  
  //       });  
  //     });  
  //   } else {  
  //     wx.showToast({  
  //       title: '今日已打卡',  
  //       icon: 'none'  
  //     });  
  //   }  
  // }  
  punchCard: function (e) {  
    const date = e.currentTarget.dataset.date;  
    const { punchCardData, days } = this.data;  
    
    // 检查是否是今天或之前的日期  
    if (new Date(date).toDateString() !== new Date().toDateString() && new Date(date) > new Date()) {  
      wx.showToast({  
        title: '不能打卡，请选择今天或之前的日期',  
        icon: 'none'  
      });  
      return;  
    }  
    
    // 更新打卡数据  
    let newPunchCardData = { ...punchCardData };  
    let isPunched = newPunchCardData[date] ? true : false;  
    
    if (!isPunched) {  
      newPunchCardData[date] = true;  
    
      // 更新连续打卡天数（这里可能需要更复杂的逻辑来准确计算连续天数）  
      let consecutiveDays = 0;  
      const dates = Object.keys(newPunchCardData).sort();  
      for (let i = dates.length - 1; i >= 0; i--) {  
        if (new Date(dates[i]) >= new Date(dates[dates.length - 1]) - (dates.length - i) * 24 * 60 * 60 * 1000) {  
          consecutiveDays++;  
        } else {  
          break;  
        }  
      }  
      // 注意：这里的连续天数计算逻辑可能不准确，因为它基于日期字符串的差异，而不是真正的连续日期。您可能需要使用更精确的方法来计算连续天数。  
    
      // 更新days数组  
      const updatedDays = days.map(day => ({  
        ...day,  
        punched: newPunchCardData[day.date] ? true : false  
      }));  
    
      this.setData({  
        punchCardData: newPunchCardData,  
        days: updatedDays,  
        consecutivePunchDays: consecutiveDays,  
        totalPunchDays: Object.keys(newPunchCardData).length  
      }, () => {  
        wx.setStorageSync('punchCardData', newPunchCardData);  
        wx.showToast({  
          title: '打卡成功',  
          icon: 'success'  
        });  
      });  
    } else {  
      wx.showToast({  
        title: '今日已打卡',  
        icon: 'none'  
      });  
    }  
  }
});